<?php

namespace YmPhp\Admin\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Query\Builder;

class Setting extends BasicModel
{
    protected $primaryKey = 'slug';
    public $incrementing = false;
    protected $fillable = ['slug', 'value'];

    /**
     * {@inheritDoc}
     */
    public function __construct(array $attributes = [])
    {
        $this->init();

        parent::__construct($attributes);
    }

    protected function init()
    {
        $connection = config('admin.database.connection') ?: config('database.default');

        $this->setConnection($connection);

        $this->setTable(config('admin.database.settings_table') ?: 'settings');
    }


    /**
     * @param $data
     */
    public function saveConfig($data,$key)
    {
        $where['key'] = $key;
        $item = serialize($data);
        self::where($where)->update(['value' => $item]);
    }

    /**
     * @param $key
     * @return array|mixed
     */
    public function getConfig($key)
    {
        $where['key'] = 'system';
        $value = self::where($where)->value('value');
        $result = unserialize($value);
        if (is_null($result)) $result[$key] = $value;
        return $result;
    }

    /**
     * @param $key
     * @return array|mixed
     */
    public function getValue($key)
    {
        $where['key'] = $key;
        $result = self::where($where)->value('value');
        return $result;

    }

}
